#pragma once

namespace xxhhdzl
{
	template<class T>
	class shared_ptr
	{
	public:
		shared_ptr(T* sp = nullptr)
			:ptr(sp)
			,count(new int(1))
		{
		}

		shared_ptr(shared_ptr<T>& sp)
			:ptr(sp.ptr)
			,count(sp.count)
		{
			(*count)++;
		}

		shared_ptr<T>& operator=(shared_ptr<T>& sp)
			{
				if (ptr == sp.ptr)
				{
					return *this;
				}

				if (--(*count) == 0)
				{
					delete ptr;
					delete count;
					ptr = count = nullptr;
				}

				ptr = sp.ptr;
				count = &(++*(sp.count));
				return *this;
			}

		T& operator*()
		{
			return *ptr;
		}

		T* operator->()
		{
			return ptr;
		}

		int use_count()
		{
			return *count;
		}

		~shared_ptr()
		{
			if (--(*count) == 0)
			{
				delete ptr;
				delete count;
				//std::cout << "delete" << std::endl;
			}
		}


		int* count;
		T* ptr;
	};
}